package io.coderyeah.ymcc.mq.consumer;

import com.alibaba.fastjson2.JSON;
import io.coderyeah.ymcc.constant.MQConstants;
import io.coderyeah.ymcc.domain.PayOrder;
import io.coderyeah.ymcc.dto.PayMsgInMQ;
import io.coderyeah.ymcc.service.IPayOrderService;
import io.coderyeah.ymcc.util.AssertUtil;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author lqs
 * @date 2022/11/4 12:51
 */
@Component
@RocketMQMessageListener(topic = MQConstants.MQ_ORDER_TOPIC,    //topic
        selectorExpression = MQConstants.MQ_ORDER_TAGS,         //tags
        consumerGroup = "service-order-producer",                     //生产者组名字
        messageModel = MessageModel.CLUSTERING)                 //消息的消费模式 CLUSTERING：集群    BROADCASTING：广播
public class CourseOrderConsumer implements RocketMQListener<MessageExt> {// 课程订单消费者 事务消息监听

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String s = new String(body, StandardCharsets.UTF_8);
        PayMsgInMQ payMsgInMQ = JSON.parseObject(s, PayMsgInMQ.class);
        // 检查订单是否重复
        PayOrder order = payOrderService.getByOrderSn(payMsgInMQ.getOrderNo());
        AssertUtil.isNull(order, "支付订单已经创建");
        // 创建支付订单
        PayOrder payOrder = new PayOrder();
        BeanUtils.copyProperties(payMsgInMQ, payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(0);
        payOrderService.insert(payOrder);
    }
}
